using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using System.IO;
namespace Super
{
	public class LangExtension : EditorWindow
	{
		[MenuItem("Framework/LangWindow")]
		public static void ShowExample()
		{
			LangExtension wnd = GetWindow<LangExtension>();
			wnd.titleContent = new GUIContent("LangExtension");
		}

		public VisualElement Root
		{
			get
			{
				return rootVisualElement;
			}
		}

		public void CreateGUI()
		{
			VisualElement root = rootVisualElement;

			VisualTreeAsset visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/FrameWork/Extension/Editor/UIToolKit/LangExtension.uxml");
			VisualElement labelFromUXML = visualTree.Instantiate();
			root.Add(labelFromUXML);

			#region
			//var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/FrameWork/Extension/Editor/UIToolKit/CommonUss.uss");
			//VisualElement labelWithStyle = new Label("Hello World! With Style");
			//labelWithStyle.styleSheets.Add(styleSheet);
			//labelWithStyle.AddToClassList("Wosers");
			//root.Add(labelWithStyle);
			#endregion

			root.Q<Button>("CustomLangBtn").RegisterCallback<ClickEvent>(evt => LangUtil.TryGenerateCustomFile());
			root.Q<Button>("ExcelLangBtn").RegisterCallback<ClickEvent>(evt => LangUtil.GenerateAllExcelFile());
			root.Q<Button>("LangKeyBtn").RegisterCallback<ClickEvent>(evt => LangUtil.GenerateKeysFile());
			root.Q<Button>("SelectFileBtn").RegisterCallback<ClickEvent>(evt => SelectLangFile());
			root.Q<Button>("SelectDireBtn").RegisterCallback<ClickEvent>(evt => SelectLangDire());
			root.Q<Button>("FileUpdateBtn").RegisterCallback<ClickEvent>(evt => FileUpdateBtn());
			root.Q<Button>("DireUpdateBtn").RegisterCallback<ClickEvent>(evt => DireUpdateBtn());
		}

		public void SelectLangFile()
		{
			string directory = GlobalUtil.GetAbsolutePath("Assets");
			string path = EditorUtility.OpenFilePanel("ѡ��Lang�������ļ�", directory, "txt");
			VisualElement root = rootVisualElement;
			root.Q<TextField>("FileTextField").value = GlobalUtil.GetAssetsRelativePath(path);
		}

		public void SelectLangDire()
		{
			string directory = GlobalUtil.GetAbsolutePath("Assets");
			string path = EditorUtility.OpenFolderPanel("ѡ��Lang������Ŀ¼", directory, "");
			VisualElement root = rootVisualElement;
			root.Q<TextField>("DireTextField").value = GlobalUtil.GetAssetsRelativePath(path);
		}

		public void UpdateLangFile(HashSet<string> langKeys ,string langPath)
		{
			if (!File.Exists(GlobalUtil.GetAbsolutePath(langPath)))
			{
				LogUtil.Log(LogType.Error, LogCategory.Lang, $"{langPath}�ļ�������");
				return;
			}
			if (!AssetUtil.AExist(langPath))
			{
				AssetUtil.ACreateOrMove(FWConfig.textAGroup, langPath);
			}
			LangDataInfo langFileInfo = LangUtil.GetDataInfoByPath(langPath);
			HashSet<string> addKeys = new HashSet<string>(langKeys);
			addKeys.ExceptWith(langFileInfo.keys);
			LangUtil.AddKeys(addKeys, langPath);
			HashSet<string> deleteKeys = new HashSet<string>(langFileInfo.keys);
			deleteKeys.ExceptWith(langKeys);
			DeleteLangKeys(deleteKeys, langFileInfo, langPath);
			LogUtil.Log(LogType.Normal, LogCategory.Lang, $"{langPath}�ļ��Ѹ���");
		}

		public void DeleteLangKeys(HashSet<string> deleteKeys, LangDataInfo langFileInfo, string path)
		{
			path = GlobalUtil.GetAbsolutePath(path);
			StreamReader SR = new StreamReader(path);
			string content = SR.ReadToEnd();
			content = content.TrimStart();
			SR.Close();
			foreach (var key in deleteKeys)
			{
				string line = $"{key}";
				if (langFileInfo.keyValuePairs.ContainsKey(key))
				{
					line = $"{key}={langFileInfo.keyValuePairs[key]}";
				}
				content = content.Replace(line + "\r\n", "");	//crlf ���з�
				content = content.Replace(line + "\n", "");		//lf ���з�
				content = content.Replace(line, "");				//��������һ��key������û�л��з�
			}
			StreamWriter SW = new StreamWriter(path);
			SW.AutoFlush = true;
			SW.Write(content);
			SW.Flush();
			SW.Close();
		}

		public void FileUpdateBtn()
		{
			string path = Root.Q<TextField>("FileTextField").value;
			HashSet<string> langKeys = LangUtil.GetKeysByAA(FWConfig.langKeysPath);
			if (!Path.GetFileName(path).StartsWith("Lang"))
			{
				LogUtil.Log(LogType.Error, LogCategory.Lang, $"{path}�ļ���������Lang��ͷ");
				return;
			}
			UpdateLangFile(langKeys, path);
			AssetDatabase.Refresh();
		}

		public void DireUpdateBtn()
		{
			string path = Root.Q<TextField>("DireTextField").value;
			HashSet<string> langKeys = LangUtil.GetKeysByAA(FWConfig.langKeysPath);
			string absolutionPath = GlobalUtil.GetAbsolutePath(path);
			if (!Directory.Exists(absolutionPath))
			{
				LogUtil.Log(LogType.Error, LogCategory.Lang, $"{path}�ļ�������");
				return;
			}
			AssetUtil.ACreateOrMove(FWConfig.textAGroup, path);

			FileInfo[] fileInfos = new DirectoryInfo(absolutionPath).GetFiles();
			if (fileInfos.Length == 0)
			{
				LogUtil.Log(LogType.Error, LogCategory.Lang, $"{path}Ŀ¼��û�ж������ļ�");
				return;
			}
			foreach (FileInfo fileInfo in fileInfos)
			{
				if (fileInfo.Name.StartsWith("Lang") && fileInfo.Extension== ".txt")
				{
					UpdateLangFile(langKeys, GlobalUtil.GetAssetsRelativePath(fileInfo.FullName));
				}
			}
			AssetDatabase.Refresh();
		}
	}
}
